package com.cangxuan.pushservice.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 手机短信发送
 * 杨刚 完成
 */
@RestController
public class SMSController extends BaseController {


    //短信发送的最小周期1分钟
    private static final long SMS_MIN_INTERVAL_MILLIS = 60000;

    @Value("${sms.signName}")
    String smsSignName;
    @Value("${sms.templateCode}")
    String smsTemplateCode;
    @Value("${sms.accessKeyId}")
    String smsAccessKeyId;
    @Value("${sms.accessKeySecret}")
    String smsAccessKeySecret;

    @Data
    public static class MessageData {
        private String mobile; //手机号码
        private int vcode;   //验证码
    }
    /**
     * 向指定用户的手机发送短信
     *
     * @param messageData
     * @return
     */
    @PostMapping("sendSMS")
    public Object sendSMS(@RequestBody MessageData messageData) throws ExecutionException, InterruptedException {
        String mobile = messageData.getMobile();     //手机号码
        int vcode = messageData.getVcode();  //验证码
        //在这里，然后调用阿里云的短信发送接口，对指定的用户手机发送短信
        String regex = "[1][345789][0-9]{9}"; //手机号码的格式：第一位只能为1，第二位可以是3，4，5，7，8，第三位到第十一位可以为0-9中任意一个数字
        if (!mobile.matches(regex)) {
            return success("电话号码格式不正确",null);
        } else {
            //可自助调整超时时间
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                            .accessKeyId(smsAccessKeyId)
                            .accessKeySecret(smsAccessKeySecret)
                            .build());

            // Configure the Client
            AsyncClient client = AsyncClient.builder()
                    .region("cn-chengdu") // Region ID
                    .credentialsProvider(provider)
                    .overrideConfiguration(ClientOverrideConfiguration
                            .create()
                            .setEndpointOverride("dysmsapi.aliyuncs.com"))
                    .build();

            // Parameter settings for API request
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName(smsSignName)
                    .templateCode(smsTemplateCode)
                    .templateParam("{\"code\":\""+ vcode +"\"}")
                    .phoneNumbers(mobile)
                    .build();

            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            SendSmsResponse resp = response.get();
            JSONObject jsonResult = JSONObject.parseObject(new Gson().toJson(resp));
            client.close();
            System.out.println(jsonResult);
            JSONObject jsonBody = jsonResult.getJSONObject("body");
            String message = jsonBody.getString("message");
            //判断短信是否发送成功
            return success(message, null);
        }
    }

}
